<?php

ini_set('display_errors', 'On');
error_reporting(E_ALL);

chdir("/home/cm/public_html/crons/");
include('../config.php');

$task_obj = new task_obj();
$last_timestamp = $task_obj->getLastEmailProcessing();

if (empty($last_timestamp))
    $criteria = '';
else
    $criteria = 'SINCE "' . date("j F Y", $last_timestamp) . '"';

$er = new Email_reader(EMAIL_TASKS_SERVER, EMAIL_TASKS_USER, EMAIL_TASKS_PASSWORD);

$inbox = $er->inbox($criteria);

//base_obj::pretty_var_dump(count($inbox));

if (!empty($inbox)) {
    $client_obj = new client_obj();
    $task_phorum_obj = new task_phorum_obj();
    $user_obj = new user_obj();
    $notify_obj = new notify_obj();
    foreach ($inbox as $i => $message) {
        $index = $message['index'];
        $header_array = json_decode(json_encode($message['header']), true);
        $header_array['date_timestamp'] = strtotime($header_array['Date']);
        $body = $message['body'];

        $domain = $header_array['from'][0]['host'];

        //base_obj::pretty_var_dump($header_array);

        $client = $client_obj->getClientByDomain($domain);

        if (error_obj::isError($client) || empty($client)) {
            continue;
        }

        //base_obj::pretty_var_dump($client);

        $email_hash = md5($header_array['date_timestamp'] . $header_array['message_id'] . $header_array['subject']);

        $task = $task_obj->getTaskByEmailHash($email_hash);

        if (error_obj::isError($task) || !empty($task)) {
            continue;
        }

        $in_data = array(
            'title' => $header_array['subject'],
            'created' => date("Y-m-d"),
            'client' => $client['klient_id'],
            'worker' => $client['contactPerson'],
            'responsible' => $client['contactPerson'],
            'deadline' => MAX_DEADLINE_DB,
            'type' => 1,
            'priority' => 3,
            'status' => 1,
            'creator' => $client['contactPerson'],
            'added' => date("Y-m-d H:i:s"),
            'updated' => '0000/00/00 00:00:00',
            'updater' => 0,
            'problem_type' => 0,
            'consult' => 0,
            'duration' => 0,
            'rate' => 0,
            'task_start' => null,
            'email_hash' => $email_hash
        );

        $newId = $task_obj->addTask($in_data);

        if (!error_obj::isError($newId)) {
            $description = 'From: ' . $header_array['from'][0]['mailbox'] . '@' . $header_array['from'][0]['host'] . ': ' . $body;
            $task_phorum = array();
            $task_phorum['user_id'] = $client['contactPerson'];
            $task_phorum['when'] = date("Y-m-d H:i:s");
            $task_phorum['type'] = 1;
            $task_phorum['text'] = base_obj::my_nl2br($description);
            $task_phorum['task_id'] = $newId;
            $res = $task_phorum_obj->addPost($task_phorum);

            if (!error_obj::isError($res)) {
                //base_obj::pretty_var_dump(1);
                $subject = "CM: New Task: " . $header_array['subject'];
                $message = 'Task: <a href="' . WWW . '?input=edit_task&task=' . $newId . '">' . $header_array['subject'] . '</a>';
                $sender = $user_obj->getUserById($client['contactPerson'], array('name', 'surname', 'email'));

                $recipients_emails = array();
                $recipients_emails[] = $header_array['from'][0]['mailbox'] . '@' . $header_array['from'][0]['host'];
                $send_result = $notify_obj->send($recipients_emails, $message, $subject, array("email" => $sender['email'], "name" => $sender['name'] . " " . $sender['surname']));
            } else {
                //base_obj::pretty_var_dump($res);
            }
        }
    }
}

$task_obj->addLastEmailProcessing();
?>
